<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/2/24 0024
 * Time: 15:18
 */
namespace App\Http\Controllers\Admin;

use App\Models\Types;

class TypesController extends Controller{

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 分类列表
     * @author wudean
     */
    public function index(){
        $data['tid']=request('tid',0);
        $data['keyword']=request('keyword','');
        //顶级分类
        $top_lists=Types::where('tid',0)->get();
        $lists=Types::getListData($data);
        foreach ($lists as $list){
            $tid_info=Types::where('id',$list->tid)->first();
            $list->tid_name=$tid_info->name;
        }
        return view('admin.type.index',compact(["top_lists","lists",'data']));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 创建页面
     * @author Deann.wu
     */
    public function create(){
        //顶级分类
         $top_lists=Types::where('tid',0)->get();
        return view('admin.type.create',compact('top_lists'));
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @name 存储分类
     * @author Deann.wu
     */
    public function store(){

        $this->validate(request(), [
            'name' => 'required|min:2|unique:types',
            'tid' => 'integer',
            'weight' => 'integer'
        ], [
            'unique'=>'该分类已经存在',
            'weight.integer'=>'权重必须是整数！'
        ]);

        $name = request('name');
        $tid = request('tid');
        $weight = request('weight');
        Types::create(compact('name', 'tid','weight'));

        return redirect('/admin/type');
    }

    /**
     * @param Types $types
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 修改页面
     * @author Deann
     */
    public function edit($id){
        $type=Types::where('id',$id)->first();
        //顶级分类
        $top_lists=Types::where('tid',0)->get();
        return view('admin.type.edit',compact(['top_lists','type']));
    }

    /**
     * @param Types $types
     * @return $this|\Illuminate\Http\RedirectResponse
     * @name 更新逻辑
     * @author Deann
     */
    public function update($id){
        $type=Types::where('id',$id)->first();
        $this->validate(request(), [
            'name' => 'required|min:2',
            'tid' => 'integer',
            'weight' => 'integer'
        ], [
            'weight.integer'=>'权重必须是整数！'
        ]);

        //检测是否当前提交
        $name = request('name');
        if($name!=$type->name){
            $f_info=Types::where('name',$name)->first();
            if($f_info){
                return back()->withErrors('该分类已经存在');
            }
        }

        $tid = request('tid');
        $weight = request('weight');
        Types::where('id',$type->id)->update(compact('name', 'tid','weight'));
        return back();
    }
}